package com.cckat.config;

import com.cckat.entity.Admin;
import com.cckat.service.AdminService;
import com.cckat.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 静海基地
 */

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @DubboReference
    private AdminService adminService;
    @DubboReference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        Admin admin = adminService.findAdminByUsername(username);
        if (admin == null) {
            return null;
        }
        //声明用户所拥有的权限集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        //通过用户id查询用户所拥有的权限的code
        List<String> permissionCodeList = permissionService.findPermissionCodeListByAdminId(admin.getId());
        for (String permissionCode : permissionCodeList) {
            if (StringUtils.isEmpty(permissionCode)) {
                continue;
            }
            authorities.add(new SimpleGrantedAuthority(permissionCode));
        }
        return new User(admin.getUsername(), admin.getPassword(), authorities);
    }
}

